package service

import (
	"fmt"
	"software/global"

	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	imageaudit "github.com/alibabacloud-go/imageaudit-20191230/v3/client"
)

type ContentAuditService struct{}

// AuditText 审核文本内容
func (c *ContentAuditService) AuditText(content string) (bool, string, error) {
	// 检查内容是否为空或默认值
	if content == "" || content == "无内容" || content == "无标题" {
		return false, "empty_content", fmt.Errorf("内容不能为空或默认值")
	}

	// 获取配置
	accessKeyID := global.Config.Aliyun.AccessKeyId
	accessKeySecret := global.Config.Aliyun.AccessKeySecret
	endpoint := global.Config.Aliyun.Endpoint // 例如：imageaudit.cn-shanghai.aliyuncs.com
	region := global.Config.Aliyun.Region     // 例如：cn-shanghai

	// 创建阿里云客户端配置
	config := &openapi.Config{
		AccessKeyId:     &accessKeyID,
		AccessKeySecret: &accessKeySecret,
		Endpoint:        &endpoint,
		RegionId:        &region,
	}

	// 创建阿里云审核客户端
	client, err := imageaudit.NewClient(config)
	if err != nil {
		return false, "", fmt.Errorf("创建阿里云审核客户端失败: %v", err)
	}

	// 创建文本审核请求
	scanTextRequest := &imageaudit.ScanTextRequest{
		Tasks: []*imageaudit.ScanTextRequestTasks{
			{
				Content: &content,
			},
		},
		Labels: []*imageaudit.ScanTextRequestLabels{
			{Label: strPtr("spam")},       // 垃圾内容
			{Label: strPtr("politics")},   // 政治敏感
			{Label: strPtr("abuse")},      // 辱骂
			{Label: strPtr("terrorism")},  // 暴恐
			{Label: strPtr("porn")},       // 色情
			{Label: strPtr("flood")},      // 灌水
			{Label: strPtr("contraband")}, // 违禁
			{Label: strPtr("ad")},         // 广告
		},
	}

	// 发送请求
	response, err := client.ScanText(scanTextRequest)
	if err != nil {
		return false, "", fmt.Errorf("发送文本审核请求失败: %v", err)
	}

	// 检查响应
	if response == nil || response.Body == nil || response.Body.Data == nil || len(response.Body.Data.Elements) == 0 {
		return false, "", fmt.Errorf("文本审核响应为空")
	}

	// 检查是否有违规内容
	for _, element := range response.Body.Data.Elements {
		if element.Results != nil {
			for _, result := range element.Results {
				// 如果建议是block，则表示内容不合规
				if result.Suggestion != nil && *result.Suggestion == "block" {
					label := "unknown"
					if result.Label != nil {
						label = *result.Label
					}
					return false, label, nil
				}
			}
		}
	}

	// 通过审核
	return true, "", nil
}

// TextFeedback 文本审核结果反馈
func (c *ContentAuditService) TextFeedback(taskID string, content string, label string) error {
	// 阿里云文本内容安全API不支持反馈，此方法保留但不实现
	return nil
}

// strPtr 返回字符串的指针
func strPtr(s string) *string {
	return &s
}
